package com.denghq.projectbuilder.component.logging.autoconfigure;

import com.denghq.projectbuilder.component.logging.listener.LoggingConfigChangeListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(RefreshScope.class)
@ConditionalOnProperty(name = "spring.cloud.refresh.enabled", matchIfMissing = true)
public class LoggingRefreshAutoConfiguration {

    private LoggingSystem loggingSystem;

    LoggingRefreshAutoConfiguration(LoggingSystem loggingSystem){
        this.loggingSystem = loggingSystem;
    }

    @Value("${spring.application.name}")
    private String appNo;


    @Bean
    @ConditionalOnMissingBean(RefreshScope.class)
    public static RefreshScope refreshScope() {
        return new RefreshScope();
    }

    @Bean
    @ConditionalOnMissingBean(LogLevelConfigProperties.class)
    public LogLevelConfigProperties logLevelConfigProperties() {
        return new LogLevelConfigProperties();
    }

    @Bean
    @ConditionalOnMissingBean(LogConfigProperties.class)
    public LogConfigProperties loggingConfigProperties() {
        return new LogConfigProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    public ContextRefresher contextRefresher(ConfigurableApplicationContext context,
                                             RefreshScope scope) {
        return new ContextRefresher(context, scope);
    }

    @Bean
    @ConditionalOnMissingBean
    public LoggingConfigChangeListener loggingConfigChangeListener(LoggingSystem loggingSystem, ContextRefresher contextRefresher, LogConfigProperties loggingConfigProperties, LogLevelConfigProperties logLevelConfigProperties) {
        return new LoggingConfigChangeListener(appNo,loggingSystem,loggingConfigProperties, logLevelConfigProperties, contextRefresher);
    }

}
